package com.wss.common.utils.toast;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilityLifecycleCallbacks;
import ohos.aafwk.ability.AbilityPackage;
import ohos.app.ElementsCallback;
import ohos.global.configuration.Configuration;
import ohos.utils.PacMap;

public class WindowHelper implements AbilityLifecycleCallbacks {

    /**
     * 栈顶 Ability
     */
    private Ability mTopAbility;

    /**
     * 用于 Ability 暂停时移除 WindowManager
     */
    private final ToastHelper mToastHelper;

    private WindowHelper(ToastHelper toast) {
        mToastHelper = toast;
    }

    static WindowHelper register(ToastHelper toast, AbilityPackage application) {
        WindowHelper window = new WindowHelper(toast);
        application.registerCallbacks(window, new ElementsCallback() {
            @Override
            public void onMemoryLevel(int i) {

            }

            @Override
            public void onConfigurationUpdated(Configuration configuration) {

            }
        });
        return window;
    }

    /**
     * 获取栈顶的 Ability
     * @return
     */
    Ability getTopAbility() {
        return mTopAbility;
    }

    @Override
    public void onAbilityStart(Ability ability) {
        mTopAbility = ability;
    }

    @Override
    public void onAbilityActive(Ability ability) {
        mTopAbility = ability;
    }

    @Override
    public void onAbilityInactive(Ability ability) {
        if (mToastHelper.isShow()) {
            mToastHelper.cancel();
        }
    }

    @Override
    public void onAbilityForeground(Ability ability) {

    }

    @Override
    public void onAbilityBackground(Ability ability) {

    }

    @Override
    public void onAbilityStop(Ability ability) {
        if (mTopAbility == ability) {
            mTopAbility = null;
        }
    }

    @Override
    public void onAbilitySaveState(PacMap pacMap) {

    }
}
